import fg from "fast-glob";
import fs from "fs-extra";
import path from "path";
import { BaseTask, TaskResult } from "./BastTask.js";
import { toolchain } from '../../toolchain.js';

/**修改Unity图片webgl压缩格式为astc8*8 */
export class ModifyUnityTextureTask extends BaseTask<void> {
    async run(): Promise<TaskResult<void>> {
        if (toolchain.option.webglRuntime == 'douyin') {
            // 查找所有图片，修改为webgl模式下采用asts8*8
            const assetsRoot = path.join(toolchain.params.workSpacePath, 'Assets');
            const imgs = await fg(['**/*.png', '**/*.jpg', '**/*.tga'], { cwd: assetsRoot });
            for (const img of imgs) {
                const metaf = path.join(assetsRoot, img + '.meta');
                const metaContent = await fs.readFile(metaf, 'utf-8');
                const lines = metaContent.split(/\r?\n/);
                let startReplace = false, replaced = false;
                for (let i = 0, len = lines.length; i < len; i++) {
                    const line = lines[i];
                    if (startReplace) {
                        if (line.match(/^\s+textureFormat: -?\d+$/)) {
                            // 51表示astc8*8
                            lines[i] = '    textureFormat: 51';
                            replaced = true;
                            break;
                        }
                    } else {
                        if (line.match(/^\s+buildTarget: WebGL$/)) {
                            startReplace = true;
                        }
                    }
                }
                if (replaced) {
                    await fs.writeFile(metaf, lines.join('\n'), 'utf-8');
                } else {
                    console.error('fail to modify texture compress format:', img);
                }
            }
        } else {
            console.log('nothing to do.');
        }
        return { success: true, errorCode: 0, data: void 0 };
    }
}
